﻿using System;

namespace XDCCManager.Model.Packs
{
	public class MovedPack : BaseModel, IPack, INavigable
	{
		private int computedNumber = -1;

		#region IPack Members

		public string Description
		{
			get
			{
				return (Source != null) ? Source.Description : null;
			}
			set
			{
				throw new NotSupportedException();
			}
		}

		public int Gets
		{
			get
			{
				return (Source != null) ? Source.Gets : -1;
			}
			set
			{
				throw new NotSupportedException();
			}
		}

		public string Note
		{
			get
			{
				return (Source != null) ? Source.Note : null;
			}
			set
			{
				throw new NotSupportedException();
			}
		}

		public int Number
		{
			get
			{
				if (computedNumber < 0)
				{
					if (Before != null)
						computedNumber = (Before as IPack).Number + 1;
					else
						computedNumber = 1;
				}
				return computedNumber;
			}
			set
			{
				throw new NotSupportedException();
			}
		}

		public int Size
		{
			get
			{
				return (Source != null) ? Source.Size : -1;
			}
			set
			{
				throw new NotSupportedException();
			}
		}

		#endregion

		#region INavigable Members

		private INavigable before;

		public INavigable Before
		{
			get { return before; }
			set
			{
				if (before != value)
				{
					bool notify = true;
					if (before != null)
						(before as System.ComponentModel.INotifyPropertyChanged).PropertyChanged -= Before_PropertyChanged;
					if ((before != null) && (value != null))
					{
						notify = (before as IPack).Number != (value as IPack).Number;
					}
					before = value;
					computedNumber = -1;
					if (before != null)
						(before as System.ComponentModel.INotifyPropertyChanged).PropertyChanged += Before_PropertyChanged;
					if (notify)
						OnPropertyChanged("Number");
				}
			}
		}

		public INavigable After { get; set; }

		private IPack source;

		public IPack Source
		{
			get { return source; }
			set
			{
				if (source != value)
				{
					if (source != null)
						(source as System.ComponentModel.INotifyPropertyChanged).PropertyChanged -= Source_PropertyChanged;
					source = value;
					if (source != null)
						(source as System.ComponentModel.INotifyPropertyChanged).PropertyChanged += Source_PropertyChanged;
				}
			}
		}

		public IPack Destination { get; set; }

		#endregion

		void Source_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
		{
			if (e.PropertyName != "Number")
				OnPropertyChanged(e.PropertyName);
		}

		void Before_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
		{
			if (e.PropertyName == "Number")
				OnPropertyChanged(e.PropertyName);
		}
	}
}
